import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import dayjs from 'dayjs'
import { saveToAPI, getFromAPI, STORAGE_KEYS } from '../utils/storage'

// todo 简单理解：Pinia 就是 Vue3 时代的“全局数据仓库”，让你不用层层 props 传递或 event 派发，
// 直接在任何组件里用 useXXXStore() 访问和操作全局状态。

export const useContainerStore = defineStore('container', () => {
  // AI添加：容器数据和激活ID，初始为空
  const containers = ref([])
  const activeContainerId = ref(null)

  // AI添加：异步初始化方法，从API加载数据
  async function initFromAPI() {
    try {
      const savedData = await getFromAPI(STORAGE_KEYS.CONTAINERS)
      containers.value = savedData.containers || []
      activeContainerId.value = savedData.activeContainerId || null
      
      // 如果没有数据，添加一些示例数据用于演示历史容器选择功能
      if (containers.value.length === 0) {
        initSampleData()
      }
    } catch (e) {
      containers.value = []
      activeContainerId.value = null
      // 添加示例数据
      initSampleData()
    }
  }

  const activeContainer = computed(() => {
    return containers.value.find(container => container.id === activeContainerId.value) || null
  })

  function createContainer(data) {
    const id = Date.now().toString()
    const newContainer = {
      id,
      title: data.title,
      description: data.description,
      category: data.category,
      estimatedTime: data.estimatedTime,
      startTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      endTime: null,
      actualTime: 0,
      status: 'active',
      evaluation: null,
      tags: data.tags || [],
      relatedPostId: data.relatedPostId || null,
      relatedReplyId: data.relatedReplyId || null
    }
    containers.value.push(newContainer)
    activeContainerId.value = id
    return newContainer // 返回完整的容器对象
  }

  function endContainer(id, evaluationData) {
    const container = containers.value.find(c => c.id === id)
    if (container) {
      container.endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      container.status = 'completed'
      container.actualTime = calculateActualTime(container.startTime, container.endTime)
      container.evaluation = {
        effectivenessScore: evaluationData.effectivenessScore,
        positiveTags: evaluationData.positiveTags || [],
        negativeTags: evaluationData.negativeTags || [],
        notes: evaluationData.notes || ''
      }
      activeContainerId.value = null
    }
  }

  function calculateActualTime(startTime, endTime) {
    const start = dayjs(startTime)
    const end = dayjs(endTime)
    return end.diff(start, 'minute')
  }

  const completedContainers = computed(() => {
    return containers.value.filter(container => container.status === 'completed')
  })

  const activeContainers = computed(() => {
    return containers.value.filter(container => container.status === 'active')
  })

  function getContainersByCategory(category) {
    if (!category) return containers.value
    return containers.value.filter(container => container.category === category)
  }

  function getContainersByStatus(status) {
    if (!status) return containers.value
    return containers.value.filter(container => container.status === status)
  }

  function searchContainersByName(keyword) {
    if (!keyword) return containers.value
    const lowerKeyword = keyword.toLowerCase()
    return containers.value.filter(container =>
      container.title.toLowerCase().includes(lowerKeyword) ||
      (container.description && container.description.toLowerCase().includes(lowerKeyword))
    )
  }

  function searchContainersByDateRange(startDate, endDate) {
    if (!startDate || !endDate) return containers.value
    return containers.value.filter(container => {
      const containerDate = new Date(container.startTime)
      return containerDate >= startDate && containerDate <= endDate
    })
  }

  function searchContainersByScoreRange(minScore, maxScore) {
    if (minScore === undefined || maxScore === undefined) return containers.value
    return containers.value.filter(container => {
      if (container.status !== 'completed' || !container.evaluation) return false
      const score = container.evaluation.effectivenessScore
      return score >= minScore && score <= maxScore
    })
  }

  // 监听数据变化，保存到API
  watch(
    [containers, activeContainerId],
    () => {
      saveToAPI(STORAGE_KEYS.CONTAINERS, {
        containers: containers.value,
        activeContainerId: activeContainerId.value
      })
    },
    { deep: true }
  )

  function setActiveContainer(container) {
    if (container && container.id) {
      activeContainerId.value = container.id
      // saveContainers() // 如有需要可补充
    }
  }

  // 初始化示例数据（用于演示历史容器选择功能）
  function initSampleData() {
    const sampleContainers = [
      {
        id: 'sample_1',
        title: '编写项目文档',
        description: '编写API接口文档和用户手册',
        category: '工作',
        estimatedTime: 60,
        startTime: dayjs().subtract(2, 'days').format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs().subtract(2, 'days').add(65, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
        actualTime: 65,
        status: 'completed',
        evaluation: {
          effectivenessScore: 4,
          positiveTags: ['#方法得当', '#高度专注'],
          negativeTags: [],
          notes: '很好地完成了文档编写，思路清晰'
        },
        tags: []
      },
      {
        id: 'sample_2',
        title: '学习Vue3新特性',
        description: '学习Composition API和Pinia状态管理',
        category: '学习',
        estimatedTime: 45,
        startTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs().subtract(1, 'day').add(50, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
        actualTime: 50,
        status: 'completed',
        evaluation: {
          effectivenessScore: 5,
          positiveTags: ['#灵感迸发', '#突破难点'],
          negativeTags: [],
          notes: '非常有收获，掌握了新的开发方式'
        },
        tags: []
      },
      {
        id: 'sample_3',
        title: '代码重构优化',
        description: '重构用户管理模块，提高代码可读性',
        category: '工作',
        estimatedTime: 90,
        startTime: dayjs().subtract(3, 'days').format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs().subtract(3, 'days').add(75, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
        actualTime: 75,
        status: 'completed',
        evaluation: {
          effectivenessScore: 3,
          positiveTags: ['#计划合理'],
          negativeTags: ['#遇到难点'],
          notes: '重构过程中遇到了一些预料之外的问题'
        },
        tags: []
      }
    ]
    
    containers.value.push(...sampleContainers)
    // 保存示例数据到本地存储
    saveToAPI(STORAGE_KEYS.CONTAINERS, {
      containers: containers.value,
      activeContainerId: activeContainerId.value
    })
  }

  // AI添加：暴露异步初始化方法
  return {
    containers,
    activeContainerId,
    activeContainer,
    completedContainers,
    activeContainers,
    createContainer,
    endContainer,
    getContainersByCategory,
    getContainersByStatus,
    searchContainersByName,
    searchContainersByDateRange,
    searchContainersByScoreRange,
    setActiveContainer,
    initFromAPI // AI添加
  }
})